#include <ArduinoMqttClient.h>
#if defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_AVR_UNO_WIFI_REV2)
  #include <WiFiNINA.h>
#elif defined(ARDUINO_SAMD_MKR1000)
  #include <WiFi101.h>
#elif defined(ARDUINO_ARCH_ESP8266)
  #include <ESP8266WiFi.h>
#elif defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_NICLA_VISION) || defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_GIGA) || defined(ARDUINO_OPTA)
  #include <WiFi.h>
#elif defined(ARDUINO_PORTENTA_C33)
  #include <WiFiC3.h>
#elif defined(ARDUINO_UNOR4_WIFI)
  #include <WiFiS3.h>
#endif

#include "arduino_secrets.h"
char ssid[] = "S6506";    // 你的WiFi名称
char pass[] = "65066506";    // 你的WiFi密码

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

// MQTT服务器信息
const char broker[]    = "iot-06z00j0umvkhbmj.mqtt.iothub.aliyuncs.com";
int        port        = 1883;
const char willTopic[] = "arduino/will";

// 重点：订阅的主题需要与发布的主题匹配（这里修改为发布日志中的主题）
const char inTopic[]   = "/k1j6lspLmdS/ESP8266_B/user/get";  // 改为发布的主题
const char outTopic[]  = "arduino/out";

// 设备认证信息（保持不变）
const char clientId[] = "k1j6lspLmdS.ESP8266_B|securemode=2,signmethod=hmacsha256,timestamp=1754572814002|";
const char username[] = "ESP8266_B&k1j6lspLmdS";
const char password[] = "636b9037880ae8f16a8e7005e0ef0ed6773104378992cdb84a1eb4fdb345c5e5";


const long interval = 10000; 
unsigned long previousMillis = 0;
int count = 0;

void setup() {
  Serial.begin(115200);
  while (!Serial) {;}  // 等待串口连接

  // 连接WiFi
  Serial.print("连接WiFi: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
    Serial.print(".");
    delay(5000);
  }
  Serial.println("\nWiFi连接成功");

  // 配置MQTT客户端
  mqttClient.setId(clientId);
  mqttClient.setUsernamePassword(username, password);

  // 设置遗嘱消息
  String willPayload = "设备离线";
  mqttClient.beginWill(willTopic, willPayload.length(), true, 1);
  mqttClient.print(willPayload);
  mqttClient.endWill();

  // 连接MQTT服务器
  Serial.print("连接MQTT服务器: ");
  Serial.println(broker);
  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT连接失败! 错误码: ");
    Serial.println(mqttClient.connectError());
    while (1);
  }
  Serial.println("MQTT服务器连接成功");

  // 设置消息接收回调
  mqttClient.onMessage(onMqttMessage);

  // 关键修正：执行实际订阅操作
  int subscribeQos = 0;  // QoS等级
  if (mqttClient.subscribe(inTopic, subscribeQos)) {
    Serial.print("成功订阅主题: ");
    Serial.println(inTopic);
  } else {
  Serial.print("订阅主题失败: ");
  Serial.println(inTopic);
}
}

void loop() {
  mqttClient.poll();  // 必须定期调用，用于接收消息和保持连接
}

// 消息接收回调函数
// 消息接收回调函数
void onMqttMessage(int messageSize) {
  // 存储接收到的主题和消息内容
  String topic = mqttClient.messageTopic();
  String payload;
  
  // 读取消息内容
  while (mqttClient.available()) {
    payload += (char)mqttClient.read();
  }
  
  // 打印接收到的信息
  Serial.println("-------------------");
  Serial.print("收到消息，主题: '");
  Serial.print(topic);
  Serial.print("'，长度: ");
  Serial.println(messageSize);
  Serial.print("内容: ");
  Serial.println(payload);
  Serial.println("-------------------");
  
  // 在这里可以添加消息处理逻辑
  // 例如判断特定命令并执行相应操作
  if (payload == "ON") {
    Serial.println("执行打开操作");
    // digitalWrite(LED_PIN, HIGH);  // 示例：控制LED
  } else if (payload == "OFF") {
    Serial.println("执行关闭操作");
    // digitalWrite(LED_PIN, LOW);   // 示例：控制LED
  }
}

    